import datetime
import gzip
import json
import random
import urllib
from urllib.parse import quote
import urllib.request
from time import sleep
from threading import Thread
from apscheduler.schedulers.background import BackgroundScheduler


from message.message_action import send_message


def another_thread(group_id, who, ws, content, left):
    if group_id == "":
        sleep(left)
        send_message(content, who, ws, "private")
        return True
    else:
        res = "[CQ:at,qq={}]".format(who) + ' ' + content
        sleep(left)
        send_message(res, group_id, ws, "group")
        return True


def get_time(time):
    curr_time = datetime.datetime.now()
    minute = 0
    hour = time.split("点")[0]
    hour = int(hour)
    if curr_time.hour > hour:
        return False
    try:
        minute = int(time.split("点")[1])
        print(minute)
    except:
        if '分' in time:
            minute = time.split("点")[1].split("分")[0]
            minute = int(minute)
    if curr_time.hour == hour:
        if curr_time.minute > minute:
            return False
    return hour, minute


class Remind:
    def __init__(self, config, ws):
        self.detect = config["detect_statement"]
        self.remind = config["remind"]
        self.ws = ws
        self.scheduler = BackgroundScheduler()

    # 启动一个线程并保存到   self.thread  中

    def remind_do(self, msg, group_id, who):
        curr_time = datetime.datetime.now()
        for key in self.remind["key_word"]:
            if key in msg:
                try:
                    content = msg.split(key)[1]
                    if get_time(msg.split(key)[0]) is False:
                        if group_id == "":
                            send_message("时间不对啊", who, self.ws, "private")
                        else:
                            send_message("时间不对啊", group_id, self.ws, "group")
                        return False
                    else:
                        hour, minute = get_time(msg.split(key)[0])
                    left = (hour - curr_time.hour) * 60 * 60 + (minute - curr_time.minute) * 60
                    Thread(target=another_thread, args=(group_id, who, self.ws, content, left)).start()
                    return True
                except:
                    return False
            else:
                pass
        return False

    # {"weather":[[who,where,time]],"news":[[who,what,time]]}
    # 每天 [x点|x点x|x点x分]提醒我[天气|新闻]
    def remind_everyday(self, msg, who):
        print("using remind_everyday")
        msg = msg[2:]
        for key_word in self.remind["key_word"]:
            if key_word in msg:
                try:
                    content = msg.split(key_word)[1]
                    for weather_key in self.remind["weather"]:
                        if weather_key in content:
                            job_id = random.randint(1000, 4000)
                            job_id = str(job_id)
                            hour, minute = get_time(msg.split(key_word)[0])
                            place = content[:len(weather_key)]
                            self.scheduler.add_job(send_weather, 'cron', day_of_week='0-6', hour=hour, minute=minute,
                                              args=[place, who, self.ws], id=job_id)
                            self.scheduler.start()
                            return [True, job_id]
                    else:
                        return [False]
                except Exception as e:
                    print(e)
                    return [False]
            else:
                return [False]
        return [False]


def send_weather(place, who, ws):
    res = ""
    url1 = 'http://wthrcdn.etouch.cn/weather_mini?city=' + urllib.parse.quote(place)
    weather_data = urllib.request.urlopen(url1).read()
    weather_data = gzip.decompress(weather_data).decode('utf-8')
    weather_dict = json.loads(weather_data)
    if weather_dict.get('desc') == 'invilad-citykey':
        res = '你输入的城市名有误，或者天气中心未收录你所在城市，不过八成是你输入的格式错了'
    elif weather_dict.get('desc') == 'OK':
        forecast = weather_dict.get('data').get('forecast')
        res = "------天气------ \n"
        res += "城市：" + weather_dict.get('data').get('city') + " \n"
        res += "温度：" + weather_dict.get('data').get('wendu') + "℃ " + " \n"
        res += "感冒：" + weather_dict.get('data').get('ganmao') + " \n"
        res += "风向：" + forecast[0].get('fengxiang') + " \n"
        res += "风级：" + forecast[0].get('fengli') + " \n"
        res += "高温：" + forecast[0].get('high') + " \n"
        res += "低温：" + forecast[0].get('low') + " \n"
        res += "天气：" + forecast[0].get('type') + " \n"
        res += "日期：" + forecast[0].get('date') + " \n"
        res += "*******************************" + " \n"
        for i in range(1, 5):
            res += '日期：' + forecast[i].get('date') + " \n"
            res += '风向：' + forecast[i].get('fengxiang') + " \n"
            res += '风级：' + forecast[i].get('fengli') + " \n"
            res += '高温：' + forecast[i].get('high') + " \n"
            res += '低温：' + forecast[i].get('low') + " \n"
            res += '天气：' + forecast[i].get('type') + " \n"
            res += '--------------------------' + " \n"

    if res == "":
        return False
    data = {
        'user_id': who,
        'message': res,
        'auto_escape': False
    }
    action = "send_private_msg"
    post_data = json.dumps({"action": action, "params": data})
    rev = ws.send(post_data)
